package dbinit;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import core.role.model.BasicRoleRules;
import core.role.model.BasicRoles;
import core.util.HibernateCoreUtil;
public class InitBasicRoles {
	public static BasicRoles getBasicRolesByUuid(Long uuid)
	{
		BasicRoles br = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				br = (BasicRoles) session.get(BasicRoles.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return br ;
	}
	public static BasicRoles getBasicRolesByName(String roleName)
	{
		BasicRoles br = null ;
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		try
		{
			transaction = session.beginTransaction();
			br = (BasicRoles)session.createCriteria(BasicRoles.class).add(Restrictions.eq("roleName", roleName)).uniqueResult();
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return br ;
	}
	public static Long doinit(String roleName, Set <Long> basicRoleRules)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		BasicRoles basicrole  = getBasicRolesByName(roleName);
		if(basicrole == null)
		{
			basicrole = new BasicRoles();
		}
		basicrole.setRoleName(roleName);
		Iterator<Long> roleRules = basicRoleRules.iterator();
		Set<BasicRoleRules> brr = new HashSet<BasicRoleRules>();
		while(roleRules.hasNext())
		{
			brr.add(InitBasicRoleRules.getBasicRoleRulesByUUID(roleRules.next()));
		}
		basicrole.setBasicRoleRules(brr);
		Long uuid = null;
		try
		{
			transaction = session.beginTransaction();
			basicrole = (BasicRoles)session.merge(basicrole);
			transaction.commit();
			uuid = basicrole.getUuid();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return uuid ;
	}

}
